// 游戏主控制器

class Game {
    constructor() {
        this.isInitialized = false;
        this.isRunning = false;
        this.isPaused = false;
        this.wasRunningBeforeHidden = false;
        this.gameMode = 'classic';
        
        // 游戏状态
        this.score = 0;
        this.combo = 0;
        this.maxLevel = 1;
        this.nextBallLevel = 1;
        
        // 游戏配置
        this.dropCooldown = 0;
        this.lastDropTime = 0;
        this.gameStartTime = 0;
        
        // 模块实例
        this.physics = null;
        this.renderer = null;
        this.ui = null;
        this.audio = null;
        
        // 绑定方法
        this.update = this.update.bind(this);
        this.handleCanvasClick = this.handleCanvasClick.bind(this);
        this.handleResize = this.handleResize.bind(this);
    }

    // 初始化游戏
    async init() {
        try {
            console.log('初始化游戏...');
            
            // 初始化音频管理器
            this.audio = new AudioManager();
            await this.audio.init();
            window.AudioManager = this.audio;
            
            // 初始化物理引擎
            const canvas = document.getElementById('gameCanvas');
            this.physics = new PhysicsEngine(canvas);
            
            // 初始化渲染器
            this.renderer = new Renderer(canvas);
            this.renderer.init(this.physics);
            
            // 初始化UI管理器
            this.ui = new UIManager();
            
            // 设置事件回调
            this.setupEventCallbacks();
            
            // 设置画布事件
            this.setupCanvasEvents();
            
            // 设置窗口事件
            this.setupWindowEvents();
            
            // 生成第一个球
            this.generateNextBall();
            
            this.isInitialized = true;
            console.log('游戏初始化完成');
            
            // 确保尺寸正确
            this.handleResize();
            
            // 显示开始界面
            this.ui.showStartScreen();
            
        } catch (error) {
            console.error('游戏初始化失败:', error);
            this.ui?.showMessage('游戏初始化失败，请刷新页面重试', 'warning');
        }
    }

    // 设置事件回调
    setupEventCallbacks() {
        // UI事件回调
        this.ui.setEventCallbacks({
            onStartGame: () => this.startGame(),
            onRestartGame: () => this.restartGame(),
            onPowerUpUsed: (type) => this.usePowerUp(type),
            onPauseToggled: (paused) => this.togglePause(paused),
            onGameModeChanged: (mode) => this.changeGameMode(mode)
        });
        
        // 物理引擎事件回调
        this.physics.setEventCallbacks({
            onMerge: (newLevel, score, x, y) => {
                console.log('物理引擎合成事件触发:', newLevel, score, x, y);
                this.handleBallMerge(newLevel - 1, newLevel, { x, y });
            },
            onGameOver: () => this.handleGameOver(),
            onBallCollision: (ball1, ball2) => this.handleBallCollision(ball1, ball2)
        });
    }

    // 设置画布事件
    setupCanvasEvents() {
        const canvas = this.renderer.canvas;
        
        // 获取正确的坐标转换函数
        const getCanvasCoordinates = (clientX, clientY) => {
            const rect = canvas.getBoundingClientRect();
            // 使用显示尺寸进行坐标转换，而不是实际像素尺寸
            const displayWidth = parseFloat(canvas.style.width) || rect.width;
            const displayHeight = parseFloat(canvas.style.height) || rect.height;
            const scaleX = displayWidth / rect.width;
            const scaleY = displayHeight / rect.height;
            return {
                x: (clientX - rect.left) * scaleX,
                y: (clientY - rect.top) * scaleY
            };
        };
        
        // 鼠标事件
        canvas.addEventListener('click', this.handleCanvasClick);
        canvas.addEventListener('mousemove', (e) => {
            if (this.isRunning && !this.isPaused) {
                const coords = getCanvasCoordinates(e.clientX, e.clientY);
                this.renderer.setMousePosition(coords.x);
            }
        });
        
        // 触摸事件
        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const coords = getCanvasCoordinates(touch.clientX, touch.clientY);
            
            this.renderer.setMousePosition(coords.x);
            // 创建模拟的鼠标事件对象，包含正确的坐标
            this.handleCanvasClick({ 
                clientX: touch.clientX, 
                clientY: touch.clientY,
                canvasX: coords.x,
                canvasY: coords.y
            });
        });
        
        canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (this.isRunning && !this.isPaused) {
                const touch = e.touches[0];
                const coords = getCanvasCoordinates(touch.clientX, touch.clientY);
                this.renderer.setMousePosition(coords.x);
            }
        });
    }

    // 设置窗口事件
    setupWindowEvents() {
        window.addEventListener('resize', this.handleResize);
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.hidden && this.isRunning && !this.isPaused) {
                this.wasRunningBeforeHidden = true;
                this.pause();
            } else if (!document.hidden && this.wasRunningBeforeHidden) {
                this.wasRunningBeforeHidden = false;
                this.resume();
            }
        });
        
        // 窗口焦点变化
        window.addEventListener('focus', () => {
            if (this.wasRunningBeforeHidden && this.isRunning) {
                this.resume();
                this.wasRunningBeforeHidden = false;
            }
        });
        
        window.addEventListener('blur', () => {
            if (this.isRunning && !this.isPaused) {
                this.wasRunningBeforeHidden = true;
                this.pause();
            }
        });
        
        // 防止页面刷新时丢失游戏状态
        window.addEventListener('beforeunload', () => {
            if (this.isRunning) {
                this.ui.saveGameData();
            }
        });
    }

    // 开始游戏
    startGame() {
        if (!this.isInitialized) {
            console.error('游戏未初始化');
            return;
        }
        
        console.log('开始游戏');
        
        this.isRunning = true;
        this.isPaused = false;
        this.gameStartTime = Date.now();
        
        // 重置游戏状态
        this.resetGameState();
        
        // 隐藏遮罩层
        this.ui.hideOverlay();
        
        // 开始游戏循环
        this.startGameLoop();
        
        // 播放背景音乐
        if (this.audio && this.audio.playBackgroundMusic) {
            this.audio.playBackgroundMusic();
        }
        
        console.log('游戏已开始');
    }

    // 重启游戏
    restartGame() {
        console.log('重启游戏');
        
        // 停止当前游戏
        this.stopGame();
        
        // 重置物理世界
        this.physics.reset();
        
        // 重置渲染器
        this.renderer.reset();
        
        // 开始新游戏
        setTimeout(() => {
            this.startGame();
        }, 100);
    }

    // 停止游戏
    stopGame() {
        this.isRunning = false;
        this.isPaused = false;
        
        // 停止背景音乐
        this.audio.stopBackgroundMusic();
        
        console.log('游戏已停止');
    }

    // 暂停/恢复游戏
    pause() {
        if (!this.isRunning) return;
        
        this.isPaused = true;
        this.physics.pause();
        this.ui.showMessage('游戏已暂停', 'info');
    }

    resume() {
        if (!this.isRunning) return;
        
        this.isPaused = false;
        this.physics.resume();
        this.ui.showMessage('游戏继续', 'info');
    }

    togglePause(paused) {
        if (paused !== undefined) {
            this.isPaused = paused;
        } else {
            this.isPaused = !this.isPaused;
        }
        
        if (this.isPaused) {
            this.pause();
        } else {
            this.resume();
        }
    }

    // 开始游戏循环
    startGameLoop() {
        const gameLoop = () => {
            if (this.isRunning) {
                this.update();
                requestAnimationFrame(gameLoop);
            }
        };
        requestAnimationFrame(gameLoop);
    }

    // 游戏更新
    update() {
        if (!this.isRunning || this.isPaused) return;
        
        const currentTime = Date.now();
        
        // 更新冷却时间
        if (this.dropCooldown > 0) {
            this.dropCooldown = Math.max(0, this.dropCooldown - (currentTime - this.lastDropTime));
        }
        this.lastDropTime = currentTime;
        
        // 更新物理引擎
        this.physics.update();
        
        // 更新渲染器
        this.renderer.update(this.physics.getBalls(), this.physics.getParticles());
        
        // 检查游戏结束条件
        if (this.physics.checkGameOver()) {
            this.handleGameOver();
        }
    }

    // 处理画布点击
    handleCanvasClick(event) {
        if (!this.isRunning || this.isPaused || this.dropCooldown > 0) {
            return;
        }
        
        // 如果事件已经包含画布坐标（来自触摸事件），直接使用
        let x;
        if (event.canvasX !== undefined) {
            x = event.canvasX;
        } else {
            // 否则计算坐标（来自鼠标事件）
            const rect = this.renderer.canvas.getBoundingClientRect();
            const displayWidth = parseFloat(this.renderer.canvas.style.width) || rect.width;
            x = (event.clientX - rect.left) * (displayWidth / rect.width);
        }
        
        // 检查点击位置是否在有效范围内
        const displayWidth = parseFloat(this.renderer.canvas.style.width) || this.renderer.canvas.getBoundingClientRect().width;
        if (x < GAME_CONFIG.CONTAINER_PADDING || x > displayWidth - GAME_CONFIG.CONTAINER_PADDING) {
            return;
        }
        
        // 投放球体
        this.dropBall(x);
    }

    // 投放球体
    dropBall(x) {
        const ball = this.physics.dropBall(x, this.nextBallLevel);
        
        if (ball) {
            // 播放投放音效
            Utils.playSound('drop');
            
            // 设置冷却时间
            this.dropCooldown = GAME_CONFIG.DROP_COOLDOWN;
            
            // 生成下一个球
            this.generateNextBall();
            
            console.log(`投放了${this.nextBallLevel}级球体`);
        }
    }

    // 生成下一个球
    generateNextBall() {
        this.nextBallLevel = Utils.generateRandomBallLevel();
        this.ui.updateNextBall(this.nextBallLevel);
    }

    // 处理球体合成
    handleBallMerge(oldLevel, newLevel, position) {
        console.log(`球体合成: ${oldLevel} -> ${newLevel}`);
        
        // 触发画布发光效果
        this.triggerMergeGlow(newLevel);
        
        // 计算分数
        const points = Utils.getMergeScore(newLevel);
        this.addScore(points);
        
        // 增加连击
        this.combo++;
        this.ui.updateCombo(this.combo);
        
        // 更新最高级球
        if (newLevel > this.maxLevel) {
            this.maxLevel = newLevel;
            this.ui.updateMaxLevel(newLevel);
        }
        
        // 播放合成音效
        Utils.playSound(`merge_${newLevel}`);
        
        // 震动反馈
        Utils.vibrate(30);
        
        // 显示浮动分数
        Utils.showFloatingText(position.x, position.y, `+${Utils.formatScore(points)}`, '#2ed573');
        
        // 连击奖励
        if (this.combo > 1) {
            const comboBonus = Math.floor(points * (this.combo - 1) * 0.1);
            if (comboBonus > 0) {
                this.addScore(comboBonus);
                Utils.showFloatingText(position.x, position.y - 30, `连击奖励 +${Utils.formatScore(comboBonus)}`, '#ff6b6b');
            }
        }
    }
    
    // 触发合成发光效果
    triggerMergeGlow(level) {
        const canvasContainer = document.querySelector('.canvas-container');
        if (canvasContainer) {
            // 移除之前的动画类
            canvasContainer.classList.remove('merge-glow');
            
            // 强制重绘
            canvasContainer.offsetHeight;
            
            // 添加发光动画类
            canvasContainer.classList.add('merge-glow');
            
            // 根据球体等级调整发光强度
            if (level >= 8) {
                // 高等级球体额外的屏幕震动效果
                this.triggerScreenShake();
            }
            
            // 动画结束后移除类
            setTimeout(() => {
                canvasContainer.classList.remove('merge-glow');
            }, 600);
        }
    }
    
    // 触发屏幕震动效果
    triggerScreenShake() {
        const gameContainer = document.getElementById('gameContainer');
        if (gameContainer) {
            gameContainer.style.animation = 'screenShake 0.3s ease-in-out';
            setTimeout(() => {
                gameContainer.style.animation = '';
            }, 300);
        }
    }

    // 处理球体碰撞
    handleBallCollision(ball1, ball2) {
        // 播放碰撞音效
        Utils.playSound('collision');
        
        // 重置连击（如果不是合成）
        if (ball1.level !== ball2.level) {
            this.combo = 0;
            this.ui.updateCombo(0);
        }
    }

    // 处理游戏结束
    handleGameOver() {
        console.log('游戏结束');
        
        this.stopGame();
        this.ui.showGameOverScreen();
        
        // 保存游戏数据
        this.ui.saveGameData();
    }

    // 增加分数
    addScore(points) {
        this.score += points;
        this.ui.updateScore(this.score);
    }

    // 使用道具
    usePowerUp(type) {
        if (!this.isRunning || this.isPaused) {
            return;
        }
        
        console.log(`使用道具: ${type}`);
        
        switch (type) {
            case 'bomb':
                this.useBomb();
                break;
            case 'magnet':
                this.useMagnet();
                break;
            case 'pause':
                this.usePauseItem();
                break;
        }
    }

    // 使用炸弹
    useBomb() {
        // 获取画布中心位置
        const centerX = this.renderer.canvas.width / 2;
        const centerY = this.renderer.canvas.height * 0.7;
        
        // 使用物理引擎的炸弹功能
        this.physics.useBomb(centerX, centerY, 100);
        
        this.ui.showMessage('💣 炸弹已使用！', 'info');
    }

    // 使用磁铁
    useMagnet() {
        // 使用物理引擎的磁铁功能
        this.physics.useMagnet();
        
        this.ui.showMessage('🧲 磁铁已使用！', 'info');
    }

    // 使用暂停道具
    usePauseItem() {
        // 暂停5秒
        this.pause();
        
        setTimeout(() => {
            if (this.isRunning) {
                this.resume();
            }
        }, 5000);
        
        this.ui.showMessage('⏸️ 时间暂停5秒！', 'info');
    }

    // 改变游戏模式
    changeGameMode(mode) {
        this.gameMode = mode;
        console.log(`游戏模式切换为: ${mode}`);
        
        // 根据模式调整游戏参数
        switch (mode) {
            case 'classic':
                // 经典模式 - 默认设置
                break;
            case 'hard':
                // 困难模式 - 更快的球体生成
                GAME_CONFIG.DROP_COOLDOWN = 300;
                break;
            case 'zen':
                // 禅模式 - 无时间限制
                GAME_CONFIG.DROP_COOLDOWN = 1000;
                break;
        }
    }

    // 重置游戏状态
    resetGameState() {
        this.score = 0;
        this.combo = 0;
        this.maxLevel = 1;
        this.dropCooldown = 0;
        
        // 重置UI
        this.ui.resetGameState();
        
        // 生成新的下一个球
        this.generateNextBall();
    }

    // 处理窗口大小变化
    handleResize() {
        if (this.renderer) {
            this.renderer.handleResize();
        }
        
        if (this.physics) {
            this.physics.recreateContainer();
        }
    }

    // 获取游戏统计
    getGameStats() {
        const playTime = this.gameStartTime ? Date.now() - this.gameStartTime : 0;
        
        return {
            score: this.score,
            maxLevel: this.maxLevel,
            combo: this.combo,
            playTime: Math.floor(playTime / 1000), // 秒
            ballsDropped: this.physics ? this.physics.getBallCount() : 0
        };
    }

    // 截图功能
    takeScreenshot() {
        if (this.renderer) {
            return this.renderer.takeScreenshot();
        }
        return null;
    }

    // 销毁游戏
    destroy() {
        console.log('销毁游戏');
        
        this.stopGame();
        
        // 移除事件监听器
        window.removeEventListener('resize', this.handleResize);
        
        // 清理模块
        if (this.physics) {
            this.physics.destroy();
        }
        
        if (this.renderer) {
            this.renderer.destroy();
        }
        
        if (this.audio) {
            this.audio.destroy();
        }
        
        this.isInitialized = false;
    }
}

// 全局游戏实例
let gameInstance = null;

// 初始化游戏
function initGame() {
    if (gameInstance) {
        gameInstance.destroy();
    }
    
    gameInstance = new Game();
    gameInstance.init();
    
    // 将游戏实例暴露到全局
    window.Game = gameInstance;
    
    return gameInstance;
}

// 页面加载完成后初始化游戏
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initGame);
} else {
    initGame();
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { Game, initGame };
}